package com.example.stockholdtrack.ui

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.example.stockholdtrack.data.StockApiService
import com.example.stockholdtrack.data.StockDataStore
import com.example.stockholdtrack.data.StockItem
import com.example.stockholdtrack.data.PositionRecord
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.Dispatchers

class StockDetailViewModel(
    private val dataStore: StockDataStore,
    private val stockCode: String
) : ViewModel() {
    
    private val _stock = MutableStateFlow<StockItem?>(null)
    val stock: StateFlow<StockItem?> = _stock.asStateFlow()
    
    private val _positionRecords = MutableStateFlow<List<PositionRecord>>(emptyList())
    val positionRecords: StateFlow<List<PositionRecord>> = _positionRecords.asStateFlow()
    
    private val _isLoading = MutableStateFlow(false)
    val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()
    
    private val stockApiService = StockApiService()
    
    init {
        // 初始化时先重新计算股票数据，然后加载
        viewModelScope.launch {
            dataStore.recalculateStockData(stockCode)
            loadStockData()
            loadPositionRecords()
        }
    }
    
    private fun loadStockData() {
        viewModelScope.launch {
            _isLoading.value = true
            try {
                val stockData = dataStore.getStockByCode(stockCode)
                _stock.value = stockData
            } finally {
                _isLoading.value = false
            }
        }
    }
    
    private fun loadPositionRecords() {
        viewModelScope.launch {
            println("DEBUG: ViewModel.loadPositionRecords - 开始加载持仓记录")
            dataStore.getPositionRecordsByStockCode(stockCode).collect { records ->
                println("DEBUG: ViewModel.loadPositionRecords - 收到 ${records.size} 条记录")
                records.forEachIndexed { index, record ->
                    println("DEBUG: ViewModel.loadPositionRecords - 索引[$index] - ID: ${record.id}, 数量: ${record.quantity}, 价格: ${record.price}")
                }
                _positionRecords.value = records
            }
        }
    }
    
    fun requestStockPrice() {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                // 设置加载状态为true
                _isLoading.value = true
                
                val currentStock = _stock.value
                if (currentStock == null) {
                    println("DEBUG: StockDetailViewModel.requestStockPrice - 股票数据为空，跳过请求")
                    _isLoading.value = false
                    return@launch
                }
                
                println("DEBUG: StockDetailViewModel.requestStockPrice - 开始请求股价: ${currentStock.name}(${currentStock.code})")
                
                val priceData = stockApiService.getStockPrice(currentStock.code)
                if (priceData != null) {
                    val updatedStock = currentStock.copy(
                        currentPrice = priceData.currentPrice
                    )
                    
                    _stock.value = updatedStock
                    dataStore.updateStock(updatedStock)
                    
                    println("DEBUG: StockDetailViewModel.requestStockPrice - 更新股票 ${currentStock.name}(${currentStock.code}) 价格: ${priceData.currentPrice}")
                } else {
                    println("DEBUG: StockDetailViewModel.requestStockPrice - 获取股票 ${currentStock.name}(${currentStock.code}) 价格失败")
                }
                
                println("DEBUG: StockDetailViewModel.requestStockPrice - 股价请求完成")
                
                // 通知UI线程刷新完成
                _isLoading.value = false
            } catch (e: Exception) {
                println("DEBUG: StockDetailViewModel.requestStockPrice - 股价请求异常: ${e.message}")
                _isLoading.value = false
            }
        }
    }
    
    fun addPositionRecord(record: PositionRecord) {
        viewModelScope.launch {
            dataStore.insertPositionRecord(record, stockCode)
            // 重新计算股票数据
            dataStore.recalculateStockData(stockCode)
            loadStockData()
            loadPositionRecords()
        }
    }
    
    fun updatePositionRecord(record: PositionRecord) {
        viewModelScope.launch {
            println("DEBUG: ViewModel.updatePositionRecord - 开始更新记录")
            dataStore.updatePositionRecord(record, stockCode)
            // 重新计算股票数据
            dataStore.recalculateStockData(stockCode)
            println("DEBUG: ViewModel.updatePositionRecord - 数据库更新完成，重新加载数据")
            loadStockData()
            loadPositionRecords()
            println("DEBUG: ViewModel.updatePositionRecord - 数据重新加载完成")
        }
    }
    
    fun deletePositionRecord(record: PositionRecord) {
        viewModelScope.launch {
            println("DEBUG: ViewModel.deletePositionRecord - 开始删除记录")
            dataStore.deletePositionRecord(record)
            // 重新计算股票数据
            dataStore.recalculateStockData(stockCode)
            println("DEBUG: ViewModel.deletePositionRecord - 数据库删除完成，重新加载数据")
            loadStockData()
            loadPositionRecords()
            println("DEBUG: ViewModel.deletePositionRecord - 数据重新加载完成")
        }
    }
    
    // 新增：重新计算股票数据的方法
    fun recalculateStockData() {
        viewModelScope.launch {
            dataStore.recalculateStockData(stockCode)
            loadStockData()
            loadPositionRecords()
        }
    }
    
    class Factory(
        private val dataStore: StockDataStore,
        private val stockCode: String
    ) : ViewModelProvider.Factory {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            if (modelClass.isAssignableFrom(StockDetailViewModel::class.java)) {
                @Suppress("UNCHECKED_CAST")
                return StockDetailViewModel(dataStore, stockCode) as T
            }
            throw IllegalArgumentException("Unknown ViewModel class")
        }
    }
} 